<template>
  <div class="weather-map">
    <h3>天气地图</h3>
    <div id="map-container" class="map-container"></div>
    <div v-if="mapError" class="map-error">
      {{ mapError }}
    </div>
    <div class="map-controls" v-if="!mapError">
      <div class="layer-switches">
        <label class="switch">
          <input type="checkbox" v-model="showRainLayer">
          <span class="slider">降水图层</span>
        </label>
        <label class="switch">
          <input type="checkbox" v-model="showWindLayer">
          <span class="slider">风力图层</span>
        </label>
        <label class="switch">
          <input type="checkbox" v-model="showTempLayer">
          <span class="slider">温度图层</span>
        </label>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'WeatherMap',
  props: {
    city: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const map = ref(null)
    const mapError = ref('')
    const showRainLayer = ref(false)
    const showWindLayer = ref(false)
    const showTempLayer = ref(false)
    const rainLayer = ref(null)
    const windLayer = ref(null)
    const tempLayer = ref(null)
    const currentMarker = ref(null)
    const districtLayer = ref(null)  // 用于存储当前显示的图层

    const initMap = async () => {
      try {
        // 检查API密钥是否配置
        const apiKey = import.meta.env.VITE_AMAP_KEY
        const securityKey = import.meta.env.VITE_AMAP_SECURITY_KEY
        console.log('API Key 配置状态:', apiKey ? '已配置' : '未配置')
        console.log('Security Key 配置状态:', securityKey ? '已配置' : '未配置')
        
        if (!apiKey) {
          throw new Error('未配置高德地图API密钥')
        }
        if (!securityKey) {
          throw new Error('未配置高德地图安全密钥')
        }

        // 设置安全配置
        window._AMapSecurityConfig = {
          securityJsCode: securityKey
        }

        // 确保地图容器存在
        const container = document.getElementById('map-container')
        if (!container) {
          throw new Error('地图容器不存在')
        }

        console.log('正在初始化地图...')
        const AMap = await AMapLoader.load({
          key: apiKey,
          version: '2.0',
          plugins: [
            'AMap.Weather',
            'AMap.Geocoder',
            'AMap.DistrictLayer'
          ]
        })

        // 创建地图实例
        map.value = new AMap.Map('map-container', {
          zoom: 11,
          viewMode: '2D',
          mapStyle: 'amap://styles/dark',
          willReadFrequently: true
        })

        // 根据城市名称设置地图中心
        const geocoder = new AMap.Geocoder()
        geocoder.getLocation(props.city, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const location = result.geocodes[0].location
            map.value.setCenter([location.lng, location.lat])
          } else {
            console.warn('地理编码失败:', status, result)
          }
        })

        // 初始化天气图层
        try {
          // 使用天气查询组件
          const weather = new AMap.Weather()
          
          // 存储天气数据的响应式引用
          const weatherData = ref({
            precipitation: 0,
            windPower: 0,
            temperature: 0
          })
          
          // 获取实时天气数据
          const getLiveWeather = async (city) => {
            try {
              const data = await new Promise((resolve, reject) => {
                weather.getLive(city, (err, data) => {
                  if (err) {
                    console.error('天气数据获取详细错误:', JSON.stringify(err))
                    reject(err)
                    return
                  }
                  resolve(data)
                })
              })
              
              console.log('成功获取天气数据:', data)
              // 更新天气数据
              weatherData.value = {
                precipitation: parseFloat(data.precipitation) || 0,
                windPower: parseInt(data.windPower) || 0,
                temperature: parseFloat(data.temperature) || 0
              }
              return data
            } catch (error) {
              console.error('获取天气数据失败:', error)
              throw error
            }
          }

          // 创建图层的方法
          const createLayer = (type) => {
            let color, opacity

            switch(type) {
              case 'rain':
                color = weatherData.value.precipitation > 0 ? '#1791fc' : '#a8d8ff'
                opacity = Math.min(0.4 + (weatherData.value.precipitation / 10), 0.9)
                break
              case 'wind':
                color = weatherData.value.windPower > 3 ? '#00cc00' : '#90EE90'
                opacity = Math.min(0.4 + (weatherData.value.windPower / 12), 0.9)
                break
              case 'temp':
                color = weatherData.value.temperature > 20 ? '#ff4500' : 
                       weatherData.value.temperature > 10 ? '#ff8c00' : '#87CEEB'
                opacity = Math.min(0.4 + (Math.abs(weatherData.value.temperature) / 40), 0.9)
                break
              default:
                return null
            }

            return new AMap.DistrictLayer.Province({
              zIndex: 10,
              opacity: opacity,
              depth: 2,
              styles: {
                'fill': color,
                'province-stroke': '#ffffff',
                'city-stroke': '#ffffff', 
                'county-stroke': '#ffffff'
              }
            })
          }

          // 清除当前图层
          const clearLayer = () => {
            if (districtLayer.value) {
              map.value.remove(districtLayer.value)
              districtLayer.value = null
            }
            if (currentMarker.value) {
              map.value.remove(currentMarker.value)
              currentMarker.value = null
            }
          }

          // 添加天气信息标记
          const addWeatherMarker = () => {
            const center = map.value.getCenter()
            const content = `
              <div class="weather-info">
                <div>温度: ${weatherData.value.temperature}°C</div>
                <div>降水量: ${weatherData.value.precipitation}mm</div>
                <div>风力: ${weatherData.value.windPower}级</div>
              </div>
            `

            const marker = new AMap.Marker({
              position: center,
              content: content,
              offset: new AMap.Pixel(0, -20)
            })

            currentMarker.value = marker
            map.value.add(marker)
          }

          try {
            // 初始获取天气数据
            await getLiveWeather(props.city)

            // 监听城市变化
            watch(() => props.city, async (newCity) => {
              if (!map.value) return
              try {
                // 更新地图中心点
                const geocoder = new AMap.Geocoder()
                geocoder.getLocation(newCity, async (status, result) => {
                  if (status === 'complete' && result.info === 'OK') {
                    const location = result.geocodes[0].location
                    map.value.setCenter([location.lng, location.lat])
                    
                    // 获取新城市的天气数据
                    await getLiveWeather(newCity)
                    
                    // 更新当前显示的图层
                    if (showRainLayer.value) {
                      switchLayer('rain')
                    } else if (showWindLayer.value) {
                      switchLayer('wind')
                    } else if (showTempLayer.value) {
                      switchLayer('temp')
                    }
                  }
                })
              } catch (error) {
                console.error('更新城市天气数据失败:', error)
                mapError.value = '获取天气数据失败'
              }
            })

            // 监听图层显示状态
            const switchLayer = (type) => {
              clearLayer()
              if (type) {
                districtLayer.value = createLayer(type)
                map.value.add(districtLayer.value)
                addWeatherMarker()
              }
            }

            watch([showRainLayer, showWindLayer, showTempLayer], ([rain, wind, temp]) => {
              // 确保只有一个图层被选中
              if (rain) {
                showWindLayer.value = false
                showTempLayer.value = false
                switchLayer('rain')
              } else if (wind) {
                showRainLayer.value = false
                showTempLayer.value = false
                switchLayer('wind')
              } else if (temp) {
                showRainLayer.value = false
                showWindLayer.value = false
                switchLayer('temp')
              } else {
                clearLayer()
              }
            }, { immediate: true })

          } catch (error) {
            console.error('初始化天气数据失败:', error)
            mapError.value = '天气数据暂时无法获取'
          }

        } catch (weatherError) {
          console.error('天气数据获取失败:', weatherError)
          mapError.value = '天气数据暂时无法获取'
        }

        // 清除错误信息
        mapError.value = ''
        
      } catch (error) {
        console.error('地图初始化失败:', error)
        mapError.value = `地图初始化失败: ${error.message}`
      }
    }

    onMounted(() => {
      initMap()
    })

    // 组件卸载时销毁地图
    onUnmounted(() => {
      if (map.value) {
        map.value.destroy()
      }
    })

    return {
      showRainLayer,
      showWindLayer,
      showTempLayer,
      mapError
    }
  }
}
</script>

<style scoped>
.weather-map {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 20px;
  box-sizing: border-box;
}

.map-container {
  flex: 1;
  width: 100%;
  min-height: 250px;
  border-radius: 10px;
  overflow: hidden;
  margin: 15px 0;
  position: relative;
}

/* 添加天气信息标记样式 */
:deep(.weather-info) {
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

:deep(.weather-info div) {
  margin: 2px 0;
}

.map-error {
  padding: 20px;
  text-align: center;
  color: #ff4757;
  background: rgba(255, 71, 87, 0.1);
  border-radius: 10px;
  margin: 15px 0;
}

.map-controls {
  margin-top: 10px;
}

.layer-switches {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.switch {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.switch input {
  display: none;
}

.slider {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  transition: all 0.3s ease;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}

.switch input:checked + .slider {
  background: rgba(74, 144, 226, 0.6);
  color: white;
}

.slider:hover {
  background: rgba(255, 255, 255, 0.2);
}

@media (max-width: 768px) {
  .weather-map {
    padding: 15px;
  }

  .map-container {
    min-height: 250px;
  }

  .layer-switches {
    gap: 10px;
  }

  .slider {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style> 